package com.example.todolist.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.todolist.dto.business.PublishDynamicDTO;
import com.example.todolist.mapper.DynamicCommentsMapper;
import com.example.todolist.model.Dynamic;
import com.example.todolist.mapper.DynamicMapper;
import com.example.todolist.response.BaseResponse;
import com.example.todolist.response.SystemResponse;
import com.example.todolist.service.DynamicService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.todolist.util.HttpServletRequestUtil;
import com.example.todolist.util.PassTimeUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author admin
 * @since 2022-02-25
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class DynamicServiceImpl extends ServiceImpl<DynamicMapper, Dynamic> implements DynamicService {

    private final DynamicMapper dynamicMapper;

    private final DynamicCommentsMapper dynamicCommentsMapper;

    @Override
    public BaseResponse publishDynamic(PublishDynamicDTO dto) {
        HttpServletRequest request = HttpServletRequestUtil.getHttpServletRequest();
        String uid = (String) request.getAttribute("uid");
        Dynamic dynamic = Dynamic
                .builder()
                .uid(uid)
                .dynamicId(IdUtil.simpleUUID())
                .avatarUrl(dto.getAvatarUrl())
                .pictureUrl(dto.getPictureUrl())
                .dynamicContent(dto.getDynamicContent())
                .nickname(dto.getNickName())
                .commentTotal(0)
                .build();
        boolean save = save(dynamic);
        if (save) {
            return SystemResponse.success();
        }
        return SystemResponse.fail("发布失败");
    }

    @Override
    public SystemResponse<List<Dynamic>> selectAllDynamicList() {
        List<Dynamic> list = dynamicMapper.selectAllDynamicList().stream().filter(Objects::nonNull).peek(dynamic -> {
            String format = PassTimeUtils.format(Date.from(dynamic.getCreateTime().atZone(ZoneId.systemDefault()).toInstant()));
            dynamic.setPassPublishTime(format);
            setListImage(dynamic, dynamic.getPictureUrl());
        }).collect(Collectors.toList());
        return SystemResponse.success(list, list.size());
    }

    @Override
    public SystemResponse<List<Dynamic>> findDynamicById(String dynamicId) {
        List<Dynamic> collect = dynamicMapper.selectDynamicById(dynamicId).stream().peek(dynamic -> {
            String format = PassTimeUtils.format(Date.from(dynamic.getCreateTime().atZone(ZoneId.systemDefault()).toInstant()));
            dynamic.setPassPublishTime(format);
            dynamic.getDynamicCommentsList().stream()
                    .filter(commentsList -> commentsList.getCommentId() != null)
                    .peek(comments -> {
                                String f = PassTimeUtils.format(Date.from(comments.getCreateTime().atZone(ZoneId.systemDefault()).toInstant()));
                                comments.setPassCommentCreateTime(f);
                            }
                    ).collect(Collectors.toList());
            dynamic.setDynamicCommentsList(dynamic.getDynamicCommentsList());
            setListImage(dynamic, dynamic.getPictureUrl());
        }).collect(Collectors.toList());
        return SystemResponse.success(collect);
    }

    @Override
    public SystemResponse<List<Dynamic>> personalDynamic() {
        HttpServletRequest request = HttpServletRequestUtil.getHttpServletRequest();
        String uid = (String) request.getAttribute("uid");
        QueryWrapper<Dynamic> wrapper = new QueryWrapper<>();
        wrapper.eq("uid", uid).orderByDesc("create_time");
        List<Dynamic> collect = this.baseMapper.selectList(wrapper).stream().filter(Objects::nonNull).peek(dynamic -> {
            String format = PassTimeUtils.format(Date.from(dynamic.getCreateTime().atZone(ZoneId.systemDefault()).toInstant()));
            dynamic.setPassPublishTime(format);
            setListImage(dynamic, dynamic.getPictureUrl());
        }).collect(Collectors.toList());
        return SystemResponse.success(collect);
    }

    @Override
    public BaseResponse deleteDynamic(String dynamicId) {
        Map<String, Object> dynamicMap = new HashMap<>(1);
        dynamicMap.put("dynamic_id", dynamicId);
        int i = this.baseMapper.deleteByMap(dynamicMap);
        if (i == 1) {
            Map<String, Object> commentMap = new HashMap<>(1);
            commentMap.put("dynamic_id", dynamicId);
            dynamicCommentsMapper.deleteByMap(commentMap);
            return SystemResponse.success();
        } else {
            return SystemResponse.fail("删除失败");
        }
    }

    public static void setListImage(Dynamic dynamic, String arrImage) {
        if (!StringUtils.isBlank(arrImage)) {
            dynamic.setListImage(new ArrayList<>(Arrays.asList(arrImage.split(","))));
        }
    }
}
